package dnbW.uiW.queryW.visual;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

import dnbW.dbW.DatabaseInfo;
import dnbW.dbW.PathExpression;
import dnbW.dbW.sucxentdbW.SucxentQueryTranslator;
import dnbW.entityW.Condition;
import dnbW.uiW.dbW.DatabaseController;
import dnbW.uiW.queryW.modelW.ComparisonNodeObject;
import dnbW.uiW.queryW.modelW.ConditionCluster;
import dnbW.uiW.queryW.modelW.ConditionNodeLeafObject;
import dnbW.uiW.queryW.modelW.JoinNodeObject;
import dnbW.uiW.queryW.modelW.XComparisonNodeObject;
import org.jdesktop.application.Task;

/**
 *
 * @author Colin
 */
public class IdentityPathSQLTask{
    // <editor-fold desc="Next table's ID">
    /**
     * The query-wise unique ID of the next table that will help to handle this query
     */
    public static int nextTableId;
    
    private String sqlQuery = null;
    
    private String nextNodeId = null;
    
    private String tempTableName = null;
    
    public ArrayList values = null;
    
    public static int resultCount;
    
    public static String tableName = null;
    String xpath = null;
    ConditionCluster currentConditionCluster = null;
    public String formatNextNodeId() {
        return controller.Controller.newQueryID + "_" + (++nextTableId);
    }
        
    public void identifyPath(DefaultMutableTreeNode node, DatabaseInfo db, PathExpression path, String value, String operator) throws Exception 
    {
        		
                ComparisonNodeObject nextObject = new ComparisonNodeObject(node, path, operator, value);
                
                DatabaseInfo contextDb = db;
    
                nextNodeId = this.formatNextNodeId();
                tempTableName = "T_" + nextNodeId;
                
                SucxentQueryTranslator translator = new SucxentQueryTranslator();
                System.out.println("Constructing " + nextNodeId);
                sqlQuery = translator.translate(((ComparisonNodeObject)nextObject).getCondition(path), tempTableName);
                
                Connection dbCon = contextDb.getDbConnection();
                Statement statement = dbCon.createStatement();
                
            if (sqlQuery != null) {
                    tableName = "T_" + controller.Controller.newQueryID + "_" + this.nextTableId;
                    String deleteTableQuery = "if exists (select * from sys.tables where name like '" + tableName + "')\n " +
                            "DROP TABLE " + tableName;
                    statement.execute(deleteTableQuery);
            }
                
                System.out.println("======================= Executing SQL ==================================");
                statement.execute(sqlQuery);
                
                RetrieveFinalResultsTask.intersectionTableNames.add(tempTableName);

                ResultSet result = statement.executeQuery("select count(*) from " + tempTableName);
                result.next();

                resultCount = result.getInt(1);               
        }
    public void identifyPath(  DatabaseInfo db,XComparisonNodeObject initObject, DefaultMutableTreeNode initialNode,DefaultMutableTreeNode currentNode, PathExpression initPath, PathExpression currentPath,String currentValue, String currentOperator,PathExpression leftJoinPath, PathExpression rightJoinPath) throws Exception 
    {
        		
                ComparisonNodeObject currentObject = new ComparisonNodeObject(currentNode, currentPath, currentOperator, currentValue);
              XComparisonNodeObject xcurrentObject=new XComparisonNodeObject(currentNode, currentPath, currentOperator, currentValue);
//                XComparisonNodeObject nextObject= initObject;
//                nextObject.setJoinBridge(new JoinNodeObject(initialNode, leftJoinPath, rightJoinPath, "="));
                xcurrentObject.setJoinBridge(new JoinNodeObject(currentNode, rightJoinPath,leftJoinPath, "="));
                DatabaseInfo contextDb = db;
                nextNodeId = this.formatNextNodeId();
                tempTableName = "T_" + nextNodeId;
                
                SucxentQueryTranslator translator = new SucxentQueryTranslator();
                System.out.println("Constructing " + nextNodeId);
//                currentConditionCluster=new ConditionCluster();
//                currentConditionCluster.addConditionNodeIntoCluster(obj);
//                ((ConditionNodeLeafObject) obj).setCombinedIdentityPathTable(tempTableName);
                sqlQuery = translator.translate(xcurrentObject.getCondition(initPath), tempTableName);
                
                Connection dbCon = contextDb.getDbConnection();
                Statement statement = dbCon.createStatement();
                
            if (sqlQuery != null) {
                    tableName = "T_" + controller.Controller.newQueryID + "_" + this.nextTableId;
                    String deleteTableQuery = "if exists (select * from sys.tables where name like '" + tableName + "')\n " +
                            "DROP TABLE " + tableName;
                    statement.execute(deleteTableQuery);
            }
                
                System.out.println("======================= Executing SQL ==================================");
                statement.execute(sqlQuery);
                
                RetrieveFinalResultsTask.intersectionTableNames.add(tempTableName);

                ResultSet result = statement.executeQuery("select count(*) from " + tempTableName);
                result.next();

                resultCount = result.getInt(1);               
        }
        public static List<String> getDetailPath(DefaultMutableTreeNode node) {
            List<String> p = new ArrayList<String>();

            for (TreeNode n : node.getPath()) {
                DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) n;
                if (dmtn.toString().equals(DatabaseInfo.SCHEMA_TREE_ROOT)) {
                    continue;
                }

                if (DatabaseController.isDataSourceNode(dmtn)) {
                    continue;
                }

                p.add(dmtn.toString());
            }

            return p;
        }
        
        public static void constructLeafNodes(List<String> detailPath)
        {
            
        }
    }
